{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4d1b897a",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/examples/llm/cleanlab.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "2e33dced-e587-4397-81b3-d6606aa1738a",
   "metadata": {},
   "source": [
    "# Cleanlab Trustworthy Language Model\n",
    "\n",
    "Cleanlab’s [Trustworthy Language Model](https://help.cleanlab.ai/tlm/) scores the trustworthiness of every LLM response in real-time, using state-of-the-art uncertainty estimates for LLMs.  Trust scoring is crucial for applications where unchecked hallucinations and other LLM errors are a show-stopper.\n",
    "\n",
    "This page demonstrates how to use TLM in place of your own LLM, to both generate responses and score their trustworthiness. That’s **not** the only way to use TLM though.\n",
    "To add trust scoring to your existing unmodified RAG application, you can instead see [this Trustworthy RAG tutorial](https://docs.llamaindex.ai/en/stable/examples/evaluation/cleanlab/).\n",
    "Beyond RAG applications, you can score the trustworthiness of responses already generated from any LLM via `TLM.get_trustworthiness_score()`.\n",
    "\n",
    "Learn more in the Cleanlab [documentation](https://help.cleanlab.ai/tlm/)."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "5863dde9-84a0-4c33-ad52-cc767442f63f",
   "metadata": {},
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "833bdb2b",
   "metadata": {},
   "source": [
    "If you're opening this Notebook on colab, you will probably need to install LlamaIndex 🦙."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4aff387e",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-index-llms-cleanlab"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9bbbc106",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad297f19-998f-4485-aa2f-d67020058b7d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.llms.cleanlab import CleanlabTLM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "152ced37-9a42-47be-9a39-4218521f5e72",
   "metadata": {},
   "outputs": [],
   "source": [
    "# set api key in env or in llm\n",
    "# get free API key from: https://cleanlab.ai/\n",
    "# import os\n",
    "# os.environ[\"CLEANLAB_API_KEY\"] = \"your api key\"\n",
    "\n",
    "llm = CleanlabTLM(api_key=\"your_api_key\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d61b10bb-e911-47fb-8e84-19828cf224be",
   "metadata": {},
   "outputs": [],
   "source": [
    "resp = llm.complete(\"Who is Paul Graham?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3bd14f4e-c245-4384-a471-97e4ddfcb40e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Paul Graham is an American computer scientist, entrepreneur, and venture capitalist. He is best known as the co-founder of the startup accelerator Y Combinator, which has helped launch numerous successful companies including Dropbox, Airbnb, and Reddit. Graham is also a prolific writer and essayist, known for his insightful and thought-provoking essays on topics ranging from startups and entrepreneurship to technology and society. He has been influential in the tech industry and is highly regarded for his expertise and contributions to the startup ecosystem.\n"
     ]
    }
   ],
   "source": [
    "print(resp)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08c1ac18",
   "metadata": {},
   "source": [
    "You also get the trustworthiness score of the above response in `additional_kwargs`. TLM automatically computes this score for all the <prompt, response> pair. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "871a9f4e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'trustworthiness_score': 0.8659043183923533}\n"
     ]
    }
   ],
   "source": [
    "print(resp.additional_kwargs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9fe68b6e",
   "metadata": {},
   "source": [
    "A high score indicates that LLM's response can be trusted. Let's take another example here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ccf4f33",
   "metadata": {},
   "outputs": [],
   "source": [
    "resp = llm.complete(\n",
    "    \"What was the horsepower of the first automobile engine used in a commercial truck in the United States?\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f02f73e5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The first automobile engine used in a commercial truck in the United States was the 1899 Winton Motor Carriage Company Model 10, which had a 2-cylinder engine with 20 horsepower.\n"
     ]
    }
   ],
   "source": [
    "print(resp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f8e6dc2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'trustworthiness_score': 0.5820799504369166}\n"
     ]
    }
   ],
   "source": [
    "print(resp.additional_kwargs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2eabbd56",
   "metadata": {},
   "source": [
    "A low score indicates that the LLM's response shouldn't be trusted.\n",
    "\n",
    "From these 2 straightforward examples, we can observe that the LLM's responses with the highest scores are direct, accurate, and appropriately detailed.<br />\n",
    "On the other hand, LLM's responses with low trustworthiness score convey unhelpful or factually inaccurate answers, sometimes referred to as hallucinations. "
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "25ad1b00-28fc-4bcd-96c4-d5b35605721a",
   "metadata": {},
   "source": [
    "### Streaming"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "13c641fa-345a-4dce-87c5-ab1f6dcf4757",
   "metadata": {},
   "source": [
    "Cleanlab’s TLM does not natively support streaming both the response and the trustworthiness score. However, there is an alternative approach available to achieve low-latency, streaming responses that can be used for your application.<br>\n",
    "Detailed information about the approach, along with example code, is available [here](https://help.cleanlab.ai/tlm/use-cases/tlm_rag/#alternate-low-latencystreaming-approach-use-tlm-to-assess-responses-from-an-existing-rag-system)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4139816d",
   "metadata": {},
   "source": [
    "## Advance use of TLM\n",
    "\n",
    "TLM can be configured with the following options:\n",
    "- **model**: underlying LLM to use\n",
    "- **max_tokens**: maximum number of tokens to generate in the response\n",
    "- **num_candidate_responses**: number of alternative candidate responses internally generated by TLM\n",
    "- **num_consistency_samples**: amount of internal sampling to evaluate LLM-response-consistency\n",
    "- **use_self_reflection**: whether the LLM is asked to self-reflect upon the response it generated and self-evaluate this response\n",
    "- **log**: specify additional metadata to return. include “explanation” here to get explanations of why a response is scored with low trustworthiness\n",
    "\n",
    "These configurations are passed as a dictionary to the `CleanlabTLM` object during initialization. <br />\n",
    "More details about these options can be referred from [Cleanlab's API documentation](https://help.cleanlab.ai/tlm/api/python/tlm/#class-tlmoptions) and a few use-cases of these options are explored in [this notebook](https://help.cleanlab.ai/tlm/tutorials/tlm_advanced/).\n",
    "\n",
    "Let's consider an example where the application requires `gpt-4` model with `128` output tokens."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c52f5179",
   "metadata": {},
   "outputs": [],
   "source": [
    "options = {\n",
    "    \"model\": \"gpt-4\",\n",
    "    \"max_tokens\": 128,\n",
    "}\n",
    "llm = CleanlabTLM(api_key=\"your_api_key\", options=options)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd2a4283",
   "metadata": {},
   "outputs": [],
   "source": [
    "resp = llm.complete(\"Who is Paul Graham?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca21e27f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Paul Graham is a British-born American computer scientist, entrepreneur, venture capitalist, author, and essayist. He is best known for co-founding Viaweb, which was sold to Yahoo in 1998 for over $49 million and became Yahoo Store. He also co-founded the influential startup accelerator and seed capital firm Y Combinator, which has launched over 2,000 companies including Dropbox, Airbnb, Stripe, and Reddit. Graham is also known for his essays on startup companies and programming languages.\n"
     ]
    }
   ],
   "source": [
    "print(resp)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fbb56628",
   "metadata": {},
   "source": [
    "To understand why the TLM estimated low trustworthiness for the previous horsepower related question, specify the `\"explanation\"` flag when initializing the TLM."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a10d1c10",
   "metadata": {},
   "outputs": [],
   "source": [
    "options = {\n",
    "    \"log\": [\"explanation\"],\n",
    "}\n",
    "llm = CleanlabTLM(api_key=\"your_api_key\", options=options)\n",
    "\n",
    "resp = llm.complete(\n",
    "    \"What was the horsepower of the first automobile engine used in a commercial truck in the United States?\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7298a69",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The first automobile engine used in a commercial truck in the United States was in the 1899 \"Motor Truck\" built by the American company, the \"GMC Truck Company.\" This early truck was equipped with a 2-horsepower engine. However, it's important to note that the development of commercial trucks evolved rapidly, and later models featured significantly more powerful engines.\n"
     ]
    }
   ],
   "source": [
    "print(resp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e3a4ee3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The proposed answer incorrectly attributes the first commercial truck in the United States to the GMC Truck Company and states that it was built in 1899 with a 2-horsepower engine. In reality, the first commercial truck is generally recognized as the \"Motor Truck\" built by the American company, the \"GMC Truck Company,\" but it was actually produced by the \"GMC\" brand, which was established later. The first commercial truck is often credited to the \"Benz Velo\" or similar early models, which had varying horsepower ratings. The specific claim of a 2-horsepower engine is also misleading, as early trucks typically had more powerful engines. Therefore, the answer contains inaccuracies regarding both the manufacturer and the specifications of the engine. \n",
      "This response is untrustworthy due to lack of consistency in possible responses from the model. Here's one inconsistent alternate response that the model considered (which may not be accurate either): \n",
      "The horsepower of the first automobile engine used in a commercial truck in the United States was 6 horsepower.\n"
     ]
    }
   ],
   "source": [
    "print(resp.additional_kwargs[\"explanation\"])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
